package com.handinfo.uimenu.window;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.lcdui.Graphics;

import com.handinfo.engine.AbstractGameScreen;
import com.handinfo.engine.GameManager;
import com.handinfo.engine.net.GameProtocol;
import com.handinfo.game.ActorItem;
import com.handinfo.game.ActorItemEquip;
import com.handinfo.game.AuctionItem;
import com.handinfo.uimenu.UIAbstractWindow;
import com.handinfo.uimenu.UIListener;
import com.handinfo.uimenu.UIManager;
import com.handinfo.uimenu.UIPopmenu;
import com.handinfo.uimenu.UITools;
import com.handinfo.uimenu.UIWindowFactory;
import com.handinfo.util.Tools;

/**
 * 拍卖列表
 * @author venizeng
 * 
 */
public class UIAuctionList extends UIAbstractWindow
{
	private final int STATE_LIST_MY_BUY = 1;// 我的拍物品记录
	private final int STATE_LIST_MY_SAIL = 2;// 我的卖物品记录
	private final int STATE_LIST_SYS_SEARCH = 3;// 当前搜索出的物品
	//
	private final String TITLE_SEARCH = "竞标";
	private final String TITLE_MYBUY = "我的竞价";
	private final String TITLE_MYSAIL = "我的商品";
	//
	private final String POP_DETAIL = "拍品信息";
	private final String POP_DETAIL_ITEM = "详细信息";
	private final String POP_COMPETITION = "竞价";
	private final String POP_YIKOUJIA = "一口价";
//	private final String POP_RESEARCH = "重新搜索";
	private final String POP_REFRESH = "刷新";
	private final String POP_ORDERTIME = "按时间排序";
	private final String POP_ORDERPRICE = "按价格排序";
	private final String POP_BACK = "返回";
	private final String POP_CANCEL = "撤销";
	//
	private final int IW = UITools.IW_RECT_CONTENT;
	private final int IH = UITools.IH_RECT_CONTENT;
	private static final int H_PRE = UITools.H_PRE << 1;
	private final int W_RECT = UITools.W_RECT;
	private final int W_CONTENT = W_RECT - (IW << 1);
	// private final int H_RECT = H_PRE * MAXROW_ITEMS + (IH << 1);
	private static final int H_RECT = UITools.H_RECT - (UITools.H_LABEL_STR + UITools.IH_RECTS);
	public static final int MAXROW_ITEMS = (H_RECT - (UITools.IH_RECT_CONTENT << 1)) / H_PRE;

	//
	private final int COLOR_STR_UNSEL = UIManager.getPaletteColor(UIManager.COLOR_WORD_NOS);
//	private final int COLOR_STR_SEL = UIManager.getPaletteColor(UIManager.COLOR_WORD_YESS);
	//
	private final String LABEL_NAME = "名称";
	private final String LABEL_PRICE = "一口价";
	//
	private String m_title = "拍卖列表";
	private AuctionItem[] m_items_auction;// server一页数据
	private int m_index_page;
	private int m_sum_page;
	private int m_index_top;
	private byte m_index_page_server;// 服务器页码
	private int m_index_sel;// 当前选中的auctionItem索引
	// 操作锁
	private boolean m_isOperLocked;
	private byte m_order = UIAuctionSearch.ORDER_MONEY_ASC ;

	public UIAuctionList(int id)
	{
		super(id);
		setBounds(UITools.X_BG, UITools.Y_BG, UITools.W_BG, UITools.H_BG);
	}

	public static final void test()
	{
		UIAuctionList auctionList = (UIAuctionList) UIWindowFactory.createWindow(UIWindowFactory.WINDOW_AUCTION_LIST);
		auctionList.m_items_auction = AuctionItem.getTestAuctionItems(auctionList.MAXROW_ITEMS);
		auctionList.setWindowStatus(auctionList.STATE_LIST_SYS_SEARCH);
		UIManager.getInstance().addWindow(auctionList);
	}

	public final void recvMessage(int orderId, DataInputStream dis) throws IOException
	{
		switch (orderId) {
			case GameProtocol.S_AUCTION_CANCEL:
				recvCancel(dis);
				break;
			case GameProtocol.S_AUCTION_YIKOUJIA:
				recvYikou(dis);
				break;
		}
		m_isOperLocked = false;
	}

	private void recvCancel(DataInputStream dis) throws IOException
	{
		byte state = dis.readByte();
		switch (state) {
			case 0:// 操作失败
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "撤销失败");
				break;
			case 1://
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "撤销 成功");
				break;
		}
	}

	private void recvYikou(DataInputStream dis) throws IOException
	{
		byte state = dis.readByte();
		switch (state) {
			case 0:// 操作失败
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "操作失败");
				break;
			case 1://
				GameManager.getInstance().m_game_message.unlockNetwork();
				m_index_page_server =0 ;
				GameManager.getInstance().m_game_message.sendAuctionSearch(2, m_index_page_server, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "购买成功，请注意查收邮件");
				break;
			case 2:// 操作失败
				GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "金额不足，无法购买");
				break;
		}
	}

	/**
	 * 获得拍卖列表数据 2012-2-23 上午11:21:30 venizeng
	 * @param dis
	 * @throws IOException
	 */
	public static final void recvSearch(DataInputStream dis) throws IOException
	{
		byte state = dis.readByte();
		if (state == 0) {
			return;
		}
		byte num = dis.readByte();
		if (num <= 0) {
			GameManager.getInstance().addSystemInfo(GameManager.SYSTEM_INFO_TYPE_B, "无符合条件道具");
			return;
		}
		byte page = dis.readByte();
		int sum = dis.readInt();
		AuctionItem[] items = new AuctionItem[num];
			for (int i = 0; i < num; i++) {
				items[i] = new AuctionItem();
				items[i].m_id_auction = dis.readLong();
				items[i].m_name_sailer = dis.readUTF();
				items[i].m_time = dis.readLong();
				items[i].m_money_auction = dis.readLong();
				items[i].m_money_yikou = dis.readLong();
				byte type = dis.readByte();
				Tools.debugPrintln("items["+i+"].m_id_auction="+items[i].m_id_auction);
				Tools.debugPrintln("items["+i+"].m_name_sailer="+items[i].m_name_sailer);
				Tools.debugPrintln("items["+i+"].m_time="+items[i].m_time);
				Tools.debugPrintln("items["+i+"].m_money_auction="+items[i].m_money_auction);
				Tools.debugPrintln("items["+i+"].m_money_yikou="+items[i].m_money_yikou);
				Tools.debugPrintln("type="+type);
				switch (type) {
					case ActorItem.TYPE_GOODS_EQUIPMENT:
						items[i].m_item = new ActorItemEquip();
						break;
					default:
						items[i].m_item = new ActorItem();
						break;
				}
				items[i].m_item.m_type = type;
				Tools.debugPrintln("items["+i+"].m_item.m_type="+items[i].m_item.m_type);
				items[i].m_item.m_guid = dis.readLong();
				Tools.debugPrintln("items["+i+"].m_item.m_guid="+items[i].m_item.m_guid);
				items[i].m_item.m_name = dis.readUTF();
				Tools.debugPrintln("items["+i+"].m_item.m_name="+items[i].m_item.m_name);
				items[i].m_item.m_num = dis.readInt();
				items[i].m_item.m_iconId = dis.readInt();
				items[i].m_item.m_iconCoverId = dis.readInt();
				
				if (type == ActorItem.TYPE_GOODS_EQUIPMENT) {
					ActorItemEquip equip = (ActorItemEquip) items[i].m_item;
					byte holeNum = dis.readByte();
					if (holeNum > 0) {
						equip.m_color_jewels = new byte[holeNum];
						equip.m_isXiangqian_jewels = new boolean[holeNum];
						for (int j = 0; j < holeNum; j++) {
							equip.m_color_jewels[j] = dis.readByte();
							equip.m_isXiangqian_jewels[j] = dis.readBoolean();
						}
					}
					
					equip.m_level_phy = dis.readByte() ;
					equip.m_level_magic = dis.readByte() ;
					equip.m_level_defence = dis.readByte() ;
				}
			}
		
		UIAuctionList list = (UIAuctionList) UIManager.getInstance().getWindowById(UIWindowFactory.WINDOW_AUCTION_LIST);
		if (list == null) {
			list = (UIAuctionList) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_AUCTION_LIST);
		}
		list.m_items_auction = items;
		list.setWindowStatus(list.STATE_LIST_SYS_SEARCH);
		
		if (list.m_items_auction != null) {
			list.m_sum_page = (sum + MAXROW_ITEMS - 1) / MAXROW_ITEMS;
			list.m_index_page = page;
		}
		list.m_index_top = 0 ;
		list.m_index_sel = 0 ;
		list.m_isOperLocked = false ;
	}

	protected void actionOnStateChanged()
	{
		switch (m_state) {
			case STATE_LIST_MY_BUY:
				m_title = TITLE_MYBUY;
				break;
			case STATE_LIST_MY_SAIL:
				m_title = TITLE_MYSAIL;
				break;
			case STATE_LIST_SYS_SEARCH:
				m_title = TITLE_SEARCH;
				break;
		}
	}

	protected void keyLogic()
	{
		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
			close();
			GameManager.getInstance().m_game_message.sendAuctionSearchClose();
			return ;
		}
		if (m_isOperLocked) {
			return;
		}
		if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
				|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
			if (m_items_auction == null) {
				return;
			}
			clickAuctionItem(m_items_auction[m_index_sel]);
		}
		else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_UP)) {
			if (m_items_auction == null) {
				return;
			}
//			m_index_sel--;
//			if (m_index_sel < m_index_top) {
//				m_index_top--;
//			}
//			m_index_page = m_index_top / MAXROW_ITEMS;
			if (m_index_sel == m_index_top) {
				dirLeft();
			}else{
				m_index_sel--;
			}
		}
		else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_DOWN)) {
			if (m_items_auction == null) {
				return;
			}
//			if (m_index_sel >= m_items_auction.length - 1) {
//				return;
//			}
//			m_index_sel++;
//			int disIndex = m_index_sel - m_index_top;
//			if (disIndex >= MAXROW_ITEMS) {
//				m_index_top++;
//			}
//			m_index_page = m_index_top / MAXROW_ITEMS;
			
			if (m_index_sel >= m_items_auction.length - 1) {
				dirRight();
			}else{
				m_index_sel++ ;
			}
		}
		else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT)) {
			dirLeft();
		}
		else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT)) {
			dirRight();
		}
	}
	
	private void dirLeft()
	{
//		if (m_items_auction == null) {
//			return;
//		}
//		if (m_index_page <= 0) {
//			return;
//		}
//		m_index_page--;
//		m_index_sel -= MAXROW_ITEMS;
//		m_index_top -= MAXROW_ITEMS;
		
		if (m_index_page_server-1 < 0) {
			return ;
		}
		m_index_page_server-= 1;
		m_isOperLocked = true;
//		GameManager.getInstance().m_game_message.sendAuctionReSearch((byte)(m_index_page_server)) ;
		
		GameManager.getInstance().m_game_message.sendAuctionSearch(1, m_index_page_server, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
	}

	private void dirRight()
	{
//		if (m_items_auction == null) {
//			return;
//		}
//		if (m_index_page >= m_sum_page - 1) {
//			return;
//		}
//		m_index_page++;
//		int disIndex = m_index_sel - m_index_top;
//		if (m_index_sel + disIndex >= m_items_auction.length) {
//			m_index_sel = m_items_auction.length - 1;
//		}
//		else {
//			m_index_sel += MAXROW_ITEMS;
//		}
//		m_index_top += MAXROW_ITEMS;
		
		if (m_index_page_server + 1 >= m_sum_page) {
			return ;
		}
		m_index_page_server += 1 ;
		m_isOperLocked = true;
//		GameManager.getInstance().m_game_message.sendAuctionReSearch((byte)m_index_page_server) ;
		GameManager.getInstance().m_game_message.sendAuctionSearch(1, m_index_page_server, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
	}

	private String[] getAuctionPopmenus()
	{
		switch (m_state) {
			case STATE_LIST_MY_BUY:
				return new String[] { POP_YIKOUJIA, POP_DETAIL, POP_ORDERTIME, POP_ORDERPRICE, POP_BACK };
			case STATE_LIST_MY_SAIL:
				return new String[] { POP_CANCEL, POP_DETAIL, POP_ORDERTIME, POP_ORDERPRICE, POP_BACK };
			case STATE_LIST_SYS_SEARCH:
				return new String[] { POP_DETAIL,POP_DETAIL_ITEM, POP_YIKOUJIA, POP_REFRESH, POP_ORDERTIME,
						POP_ORDERPRICE, POP_BACK };
		}
		return null;
	}

	private void clickAuctionItem(final AuctionItem item)
	{
		final String[] menus = getAuctionPopmenus();
		final UIPopmenu popmenu = (UIPopmenu) UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_POPMENU);
		popmenu.setPopmenus(menus);
		popmenu.setCentre();
		popmenu.addListener(new UIListener() {

			public void actionPerformed()
			{
				if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_LEFT_SOFT)
						|| AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_A)) {
					int index = popmenu.getCurrentIndex();
					UIManager.getInstance().removeWindow(popmenu);
					String temp = menus[index];
					if (temp == POP_DETAIL) {
						actionDetail(item);
					}else if (temp == POP_DETAIL_ITEM) {
						actionDetailItem(item) ;
					}
					else if (temp == POP_COMPETITION) {
						actionCompetition(item);
					}
					else if (temp == POP_YIKOUJIA) {
						actionYikou(item);
					}
//					else if (temp == POP_RESEARCH) {
//						actionResearch(item);
//					}
					else if (temp == POP_REFRESH) {
						actionRefresh(item);
					}
					else if (temp == POP_ORDERTIME) {
						actionOrderTime(item);
					}
					else if (temp == POP_ORDERPRICE) {
						actionOrderPrice(item);
					}
					else if (temp == POP_CANCEL) {
						actionCancel(item);
					}
					else if (temp == POP_BACK) {

					}
				}
				else if (AbstractGameScreen.haveKeyPressed(AbstractGameScreen.GK_RIGHT_SOFT)) {
					UIManager.getInstance().removeWindow(popmenu);
				}
			}

			private void actionDetailItem(AuctionItem item)
			{
				GameManager.getInstance().m_game_message.sendActorItemDetailForAuction(item.m_item.m_guid);
			}

			private void actionDetail(AuctionItem item)
			{
				// 发送item
				GameManager.getInstance().m_game_message.sendAuctionDetail(item.m_id_auction);
			}

			private void actionCompetition(AuctionItem item)
			{
				// 进入竞价
			}

			private void actionYikou(AuctionItem item)
			{
				// 发送一口价购买
				GameManager.getInstance().m_game_message.sendAuctionYikou(item.m_id_auction);
				m_isOperLocked = true;
			}

//			private void actionResearch(AuctionItem item)
//			{
//				// 返回到搜索界面
//				close();
//				if (UIManager.getInstance().getWindowById(UIWindowFactory.WINDOW_AUCTION_SEARCH) == null) {
//					UIManager.getInstance().createWindow(UIWindowFactory.WINDOW_AUCTION_SEARCH);
//				}
//			}

			private void actionRefresh(AuctionItem item)
			{
				// 重新搜索
//				GameManager.getInstance().m_game_message.sendAuctionReSearch(m_index_page_server);
				m_index_page_server = 0 ;
				GameManager.getInstance().m_game_message.sendAuctionSearch(2, m_index_page_server, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
				m_isOperLocked = true;
			}

			private void actionOrderTime(AuctionItem item)
			{
				// 按时间排序
//				m_items_auction = AuctionItem.orderByTime(m_items_auction);
				m_order = m_order == UIAuctionSearch.ORDER_TIME_ASC ? UIAuctionSearch.ORDER_TIME_DES: UIAuctionSearch.ORDER_TIME_ASC ;
				GameManager.getInstance().m_game_message.sendAuctionSearch(2, 0, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
			}

			private void actionOrderPrice(AuctionItem item)
			{
				// 按价格排序
//				m_items_auction = AuctionItem.orderByPrice(m_items_auction);
				m_order = m_order == UIAuctionSearch.ORDER_MONEY_ASC ? UIAuctionSearch.ORDER_MONEY_DES: UIAuctionSearch.ORDER_MONEY_ASC ;
				GameManager.getInstance().m_game_message.sendAuctionSearch(2, 0, UIAuctionList.MAXROW_ITEMS,m_order, 2, 2, 2, 2, 2, 2, 2,"", "") ;
			}

			protected void actionCancel(AuctionItem item)
			{
				// 撤销竞价道具
				GameManager.getInstance().m_game_message.sendAuctionCancel(item.m_id_auction);
			}
		});
	}

	private final int W_NAME = 100;
	private final int W_MONEY = 95;
	private final String MONEY = "金钱：";

	protected void paintContent(Graphics g)
	{
		UITools.paintBackGround(g, m_x, m_y, m_w, m_h, m_title);
		int tempY = m_y + UITools.INITY_CONTENT;
		int tempX = m_x + UITools.INITX_CONTENT;
		UITools.paintTitle(g, tempX, tempY, W_NAME, LABEL_NAME);
		tempX += (W_NAME + UITools.IW_RECT_CONTENT);
		UITools.paintTitle(g, tempX, tempY, W_MONEY, LABEL_PRICE);
		tempY += UITools.IH_RECTS ;
		tempY += (UITools.H_PRE + UITools.IH_RECT_CONTENT);
		tempX = m_x + UITools.INITX_CONTENT;
		UITools.paintContentRect(g, tempX, tempY, W_RECT, H_RECT);
		paintItems(g, tempX + IW, tempY + IH);
		//#if screen == "320240"
		//# UITools.paintMoneyGameRB(g, tempX + IW + W_CONTENT - UITools.IW_RECT_CONTENT, tempY+H_RECT-20, GameManager.getInstance().m_role.m_money_game,false,MONEY,Tools.YELLOW,Tools.BLACK);
		//#else
		UITools.paintMoneyGameRB(g, tempX + IW + W_CONTENT - UITools.IW_RECT_CONTENT, tempY+H_RECT-2, GameManager.getInstance().m_role.m_money_game,false,MONEY,Tools.YELLOW,Tools.BLACK);
		//#endif
		
		UITools.paintPage(g, m_x + (m_w >> 1), m_y + m_h - 8, m_index_page, m_sum_page);
	} 

	private void paintItems(Graphics g, int x, int y)
	{
		if (m_items_auction == null) {
			return;
		}
		int tempY = y;
		boolean isFocused = false;
		int fosY = y;
		for (int i = 0; i < MAXROW_ITEMS; i++) {
			int index = i + m_index_top;
			if (index >= m_items_auction.length) {
				break;
			}
			isFocused = index == m_index_sel;
			paintItem(g, x, tempY, m_items_auction[index], isFocused);
			if (isFocused) {
				fosY = tempY;
			}
			tempY += H_PRE;
		}
		UITools.drawSelectBox(g, x, fosY, UITools.W_CONTENT, H_PRE);
	}

	/**
	 * 绘制一个auctionItem
	 * @param g
	 * @param x
	 * @param y
	 * @param item
	 * @param isSel
	 */
	private void paintItem(Graphics g, int x, int y, AuctionItem item, boolean isSel)
	{
		if (item == null) {
			return;
		}
		if (item.m_item == null) {
			return;
		}
		UITools.paintInputRect(g, x, y, W_CONTENT, H_PRE, false);
		int tempY = y + IH ;
		int tempX = x + IW ;
		UITools.paintActorItem(g, tempX,tempY, item.m_item);
		tempX += UITools.W_BAG + UITools.IW_RECTS ;
		if (item.m_item.m_name != null) {
			if (item.m_item instanceof ActorItemEquip) {
				String temp = null ;
				ActorItemEquip equip = (ActorItemEquip) item.m_item ;
				if (equip.m_level_defence > 0) {
					temp = "+" + String.valueOf(equip.m_level_defence);
					g.setColor(Tools.YELLOW);
					g.drawString(temp, tempX, tempY, 0);
					tempX += AbstractGameScreen.s_font.stringWidth(temp);
				} else {
					if (equip.m_level_phy > 0) {
						temp = "+" + String.valueOf(equip.m_level_phy);
						g.setColor(Tools.RED);
						g.drawString(temp, tempX, tempY, 0);
						tempX += AbstractGameScreen.s_font.stringWidth(temp);
					}
					if (equip.m_level_magic > 0) {
						if (equip.m_level_phy > 0) {
							temp = "/+" + String.valueOf(equip.m_level_magic);
						} else {
							temp = "+" + String.valueOf(equip.m_level_magic);
						}
						g.setColor(0x2d9cff);
						g.drawString(temp, tempX, tempY, 0);
						tempX += AbstractGameScreen.s_font.stringWidth(temp);
					}
				}
			}
			tempX += 2 ;
			g.setColor(COLOR_STR_UNSEL);
			g.drawString(item.m_item.m_name, tempX , tempY, 0);
			tempX = x + IW ;
			tempY += (AbstractGameScreen.FONT_H  > UITools.H_BAG ? AbstractGameScreen.FONT_H  : UITools.H_BAG);
			if (item.m_item instanceof ActorItemEquip) {
				ActorItemEquip equip = (ActorItemEquip) item.m_item ;
				ActorItemEquip.drawJewel(g, tempX, tempY, equip);
			}
		}
		
		UITools.paintMoneyGameRB(g, x  + W_CONTENT - UITools.IW_RECT_CONTENT, y + H_PRE, item.m_money_yikou,false);
	}
}
